package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteDetailActivity_Manager;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteNewVoteActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * Fragment-表决
 */
public class ProVoteFragment extends Fragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";

    private RecyclerView mRecyclerView;
    private String mProjectId;
    private String mProjectType;
    private VoteAdapter mAdapter;
    private List<ProVote> mData;

    private int page = 1;
    private SwipeRefreshLayout swipe;

    public static ProVoteFragment newInstance(int page, String infoid) {
        Bundle args = new Bundle();
        args.putString("infoid", infoid);
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        ProVoteFragment tripFragment = new ProVoteFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    public static ProVoteFragment newInstance(int page, String infoid, String type) {
        Bundle args = new Bundle();
        args.putString("infoid", infoid);
        args.putString("infotype", type);
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        ProVoteFragment tripFragment = new ProVoteFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("zhong", "onCreate: ProVoteFragment");
        EventBus.getDefault().register(this);
        mProjectId = getArguments().getString("infoid");
        mProjectType = getArguments().getString("infotype");
        mData = new ArrayList<>();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_VOTE)) {
            onRefresh();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_detailpro_vote, container, false);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        swipe = view.findViewById(R.id.swipe);
        view.findViewById(R.id.tv_pro_module_item_add).setOnClickListener(this);
        view.findViewById(R.id.ll_pro_module_item_add).setOnClickListener(this);

        initAdapter(mData);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipe.setColorSchemeColors(0xff25b6ed, 0xff6dbcdb, 0xfff0b650, 0xffff534e, 0xffbed73d, 0xff04bfbf,
                0xffff530d, 0xff61bc46);
        swipe.setOnRefreshListener(this);
        refreshAction();
        onRefresh();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_pro_module_item_add:
            case R.id.tv_pro_module_item_add:
                Intent intent = new Intent(getActivity(), ProVoteNewVoteActivity.class);
                intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                intent.putExtra(ProVoteNewVoteActivity.KEY_PROJECTTYPE, mProjectType);
                startActivity(intent);
        }
    }


    private void refreshAction() {
        View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
        View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
        TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
        TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
        TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
        tv_pro_module_nodata_tip.setText("还没有任何表决事项记录");
        tv_pro_module_item_add.setText("新建表决事项");
        tv_pro_module_item_add0.setText("新建表决事项");

        if (BankruptcyApp.curProPermission == BankruptcyApp.PROPERMISSION_MANAGER) {
            if (mData.size() > 0) {
                ll_pro_module_item_add.setVisibility(View.VISIBLE);
                area_pro_module_nodata_tip.setVisibility(View.GONE);
            } else {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                tv_pro_module_item_add.setVisibility(View.VISIBLE);
            }
        } else {
            if (mData.size() > 0) {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.GONE);
            } else {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                tv_pro_module_item_add.setVisibility(View.GONE);
            }
        }
    }

    private void initAdapter(List<ProVote> data) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new VoteAdapter(getActivity(), R.layout.fragment_pro_detailpro_vote_item_manager, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);
        //设置item点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.item_vote:
                        Intent intent = new Intent(getActivity(), ProVoteDetailActivity_Manager.class);
                        intent.putExtra(ProVoteDetailActivity_Manager.KEY_ID, mData.get(position).getId());
                        startActivity(intent);
                        break;
                }
            }
        });
        mAdapter.setEnableLoadMore(true);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                Log.i("zhong", "onLoadMoreRequested: ====" + page);
                getList();
            }
        }, mRecyclerView);
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        page = 1;
        getList();
    }


    class VoteAdapter extends BaseQuickAdapter<ProVote, BaseViewHolder> {
        int mLayoutId;

        public VoteAdapter(Context context, int LayoutId, List<ProVote> str) {
            super(R.layout.fragment_pro_detailpro_vote_item_manager, str);
//            Log.e("=========----====provote",LayoutId+"");
            mLayoutId = R.layout.fragment_pro_detailpro_vote_item_manager;
        }

        @Override
        public void convert(BaseViewHolder helper, ProVote info) {
            helper.setText(R.id.tv_vote_name, info.getTitle());
            helper.setText(R.id.tv_vote_type, ProVote.TYPES.get(info.getType()));
            if (info.getType() == 1) {
                helper.setTextColor(R.id.tv_vote_type, getResources().getColor(R.color.pro_vote_type_1));
            } else {
                helper.setTextColor(R.id.tv_vote_type, getResources().getColor(R.color.pro_vote_type_2));
            }


            helper.setText(R.id.tv_vote_time_start, "开始时间：" + DateFormatUtils.long2Str(info.getStartTime(), true));
            helper.setText(R.id.tv_vote_time_end, "结束时间：" + DateFormatUtils.long2Str(info.getEndTime(), true));
            helper.setText(R.id.tv_vote_courtHolding, ProVote.COURTHOLDINGs.get(info.isCourtHolding()));

            if (info.isCourtHolding()) {
                if (info.getCourtHoldingResult() != 0) {
                    helper.setGone(R.id.tv_vote_courtHolding, false);
                    helper.setVisible(R.id.tv_vote_courtHoldingResult, true);
                    switch (info.getCourtHoldingResult()) {
                        case 1:
//                        viewHolder.tv_vote_courtHoldingResult.setText("法院裁定认可");
                            helper.setText(R.id.tv_vote_courtHoldingResult, "法院裁定认可");
                            break;
                        case 2:
                            helper.setText(R.id.tv_vote_courtHoldingResult, "法院裁定不认可");
//                        viewHolder.tv_vote_courtHoldingResult.setText("法院裁定不认可");
                            break;
                        case 3:
                            helper.setText(R.id.tv_vote_courtHoldingResult, "法院裁定通过");
//                        viewHolder.tv_vote_courtHoldingResult.setText("法院裁定通过");
                            break;
                    }

                } else {
                    helper.setGone(R.id.tv_vote_courtHoldingResult, false);
                }
            }
//            helper.setText(R.id.tv_vote_courtHoldingResult,
//                    ProVote.COURTHOLDINGRESULTS.get(info.getCourtHoldingResult()));
            helper.setImageDrawable(R.id.iv_voteimg,
                    getResources().getDrawable(ProVote.STATUSIMGS.get(info.getStatus())));

            helper.addOnClickListener(R.id.item_vote);
        }
    }

    public void getList() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        Network.getAPIService()
                .getVoteList_Manager(userToken, mProjectId, page, 10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data").getAsJsonObject("pageData");
                        JsonArray arr = data.getAsJsonArray("list");
                        int total = data.get("totalCount").getAsInt();
                        List<ProVote> list = ProVote.parse(arr);
                        if (page == 1)
                            mData.clear();
                        page++;
                        mData.addAll(list);
                        if (mData.size() < total) {
                            mAdapter.loadMoreComplete();
                        } else {
                            mAdapter.loadMoreEnd();
                        }
                        refreshAction();
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCompleted() {
                        swipe.setRefreshing(false);
                        mAdapter.setEnableLoadMore(true);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

}
